import { IDEFormRawItem, IHtmlItem, ITextItem } from '@ibiz/model-core';
import { useNamespace } from '@ibiz-template/vue3-util';
import { computed, defineComponent, PropType, ref, Ref, watch } from 'vue';
import { FormRawItemController } from '@ibiz-template/runtime';
import './form-rawitem.scss';

export const FormRawItem = defineComponent({
  name: 'IBizFormRawItem',
  props: {
    modelData: {
      type: Object as PropType<IDEFormRawItem>,
      required: true,
    },
    controller: {
      type: FormRawItemController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('form-raw-item');
    const c = props.controller;

    // 传入内容
    const content: Ref<string | number | undefined> = ref('');

    // 是否显示表单默认内容
    const showFormDefaultContent = computed(() => {
      if (
        props.controller.form.controlParams &&
        props.controller.form.controlParams.editmode === 'hover'
      ) {
        return true;
      }
      return false;
    });

    watch(
      () => c.data,
      async newVal => {
        if (newVal) {
          const rawItemModel = c.model.rawItem;
          if (!rawItemModel) {
            return;
          }
          let rawItemContent = '';
          const obj = { ...newVal };
          if (rawItemModel.contentType === 'RAW') {
            rawItemContent = (rawItemModel as ITextItem).caption!;
          } else if (rawItemModel.contentType === 'HTML') {
            rawItemContent = (rawItemModel as IHtmlItem).content!;
          }
          if (rawItemContent && rawItemModel.templateMode) {
            rawItemContent = await ibiz.util.hbs.render(
              rawItemContent.replaceAll('//n', '\n'),
              Object.assign(obj, { data: { ...newVal } }),
            );
          }
          content.value = rawItemContent;
        }
      },
      {
        immediate: true,
      },
    );

    return { ns, content, showFormDefaultContent };
  },
  render() {
    if (!this.controller.state.visible) {
      return null;
    }
    return (
      <iBizRawItem
        class={[
          this.ns.b(),
          ...this.controller.containerClass,
          this.ns.is('show-default', this.showFormDefaultContent),
        ]}
        rawItem={this.modelData}
        content={this.content}
        onClick={(event: MouseEvent) => this.controller.onClick(event)}
      ></iBizRawItem>
    );
  },
});

export default FormRawItem;
